﻿using Mysoft.Upgrade.HelpTool.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Mysoft.Upgrade.HelpTool.Business
{
    /// <summary>
    /// 替换enum
    /// </summary>
    public class ReplaceEnumBusiness
    {
        private readonly List<EnumReplaceDetail> _enumReplaceDetails;
        private readonly string _path;

        public ReplaceEnumBusiness(List<EnumReplaceDetail> enumReplaceDetails, string path)
        {
            this._enumReplaceDetails = enumReplaceDetails;
            this._path = path;
        }

        /// <summary>
        ///开始替换
        /// </summary>
        public void StartReplace()
        {
            DirectoryInfo dic = new DirectoryInfo(this._path);

            Replace(dic);
        }

        /// <summary>
        /// 循环替换
        /// </summary>
        /// <param name="dicInfo"></param>
        private void Replace(DirectoryInfo dicInfo)
        {
            foreach (DirectoryInfo item in dicInfo.GetDirectories())
            {
                Replace(item);
            }

            foreach (FileInfo file in dicInfo.GetFiles())
            {
                if (string.Equals(file.Extension, ".config", StringComparison.OrdinalIgnoreCase) == false)
                {
                    continue;
                }
                ReplaceConfig(file);
            }
        }

        /// <summary>
        /// 替换文件
        /// </summary>
        /// <param name="file"></param>
        private void ReplaceConfig(FileInfo file)
        {
            String content = File.ReadAllText(file.FullName);
            foreach (var replaceEnum in _enumReplaceDetails)
            {
                content = content.Replace(replaceEnum.OldEnum, replaceEnum.NowEnum);
            }

            //重新写入文件
            using (StreamWriter sW = new StreamWriter(file.FullName))
            {
                sW.Write(content);
            }
        }

    }
}
